package postlogic

import (
	"context"

	"go-zero-admin/apps/system/cmd/rpc/internal/svc"
	"go-zero-admin/apps/system/cmd/rpc/syspb"
	"go-zero-admin/apps/system/model"
	"go-zero-admin/pkg/constant"
	"go-zero-admin/pkg/tool"
	"go-zero-admin/pkg/xerr"

	"github.com/Masterminds/squirrel"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type UpPostLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
	isExPostNameCodeLogic *IsExPostNameCodeLogic
}

func NewUpPostLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpPostLogic {
	return &UpPostLogic{
		ctx:                   ctx,
		svcCtx:                svcCtx,
		Logger:                logx.WithContext(ctx),
		isExPostNameCodeLogic: NewIsExPostNameCodeLogic(ctx, svcCtx),
	}
}

func (l *UpPostLogic) UpPost(in *syspb.UpPostReq) (*syspb.UpPostResp, error) {
	post := in.GetParams()
	if post == nil || post.GetPostId() == 0 || post.GetPostName() == "" ||
		post.GetPostCode() == "" || post.GetUpdateUser() == "" {
		return nil, errors.Wrapf(xerr.NewErrMsg("更新岗位失败：参数错误"),
			tool.GetErrMsgFormat("update post"), "params is not existed", in)
	}

	// 校验参数重复
	isExistResp, err := l.isExPostNameCodeLogic.IsExPostNameCode(&syspb.IsExPostNameCodeReq{
		Name:    post.GetPostName(),
		Code:    post.GetPostCode(),
		IsNotId: post.GetPostId(),
	})
	if err != nil {
		return nil, err
	}
	if isExistResp.GetIsExist() {
		return nil, errors.Wrapf(xerr.NewErrMsg("更新岗位："+post.GetPostName()+" 失败，名称或编码已经存在"),
			tool.GetErrMsgFormat("update post"), "post name or code is existed", post)
	}

	// 如果要禁用，但该岗位已分配，则不允许更新禁用
	if post.Status == constant.PostStatusOff {
		// 直接使用model查询，避免循环依赖
		count, err := l.svcCtx.SysUserPostModel.FindCount(l.ctx, l.svcCtx.SysUserPostModel.CountBuilder("1").
			Where(squirrel.Eq{"post_id": post.PostId}))
		if err != nil || count > 0 {
			return nil, errors.Wrapf(xerr.NewErrMsg("更新岗位失败：岗位："+post.GetPostName()+" 已分配，不允许禁用"),
				tool.GetErrMsgFormat("update post"), "post is assigned", post)
		}
	}

	// 转换数据
	one, err := l.svcCtx.SysPostModel.FindOne(l.ctx, post.GetPostId())
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrFindOneCode(err, model.ErrNotFound),
			tool.GetErrMsgFormat("update post"), err, in)
	}
	one.PostId = post.GetPostId()
	one.PostCode = post.GetPostCode()
	one.PostName = post.GetPostName()
	one.PostSort = post.GetUpdateTime()
	one.Status = post.GetStatus()
	one.Remark = post.GetRemark()
	one.UpdateUser = post.GetUpdateUser()

	// 更新数据
	err = l.svcCtx.SysPostModel.UpdateEx(l.ctx, nil, one)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrFindOneCode(err, model.ErrNotFound),
			tool.GetErrMsgFormat("update post"), err, in)
	}

	return &syspb.UpPostResp{}, nil
}
